package com.durian.app.lifecycle.api;

import android.app.Application;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;

import com.durian.app.lifecycle.annotation.LifeCycleConfig;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 说明：AppLifeCycleManager
 * <p/>
 * 作者：fanly
 * <p/>
 * 类型：Class
 * <p/>
 * 时间：2019-06-12 17:42
 * <p/>
 * 版本：version 1.0
 */
public class AppLifeCycleManager {

    private static List<IAppLike> APP_LIKE_LIST          = new ArrayList<>();
    private static boolean        REGISTER_BY_PLUGIN     = false;
    private static Set<String> appLikeMap;

    public static void addAppLike(String path){
        if (appLikeMap == null){
            appLikeMap = new HashSet<>();
        }
        appLikeMap.add(path);
    }

    /**
     * 初始化
     *
     * @param application
     */
    public static void init(Application application) {
        if (!REGISTER_BY_PLUGIN) {
            scanClassFile(application);
            REGISTER_BY_PLUGIN = true;
        }

        Collections.sort(APP_LIKE_LIST, new AppLikeComparator());
        for (IAppLike appLike : APP_LIKE_LIST) {
            appLike.onCreate(application);
        }
    }

    public static void terminate() {
        for (IAppLike appLike : APP_LIKE_LIST) {
            appLike.onTerminate();
        }
    }

    public static void lowMemory() {
        for (IAppLike appLike : APP_LIKE_LIST) {
            appLike.onLowMemory();
        }
    }

    private static void scanClassFromAndroidManifest(Application application){
        try {
            ApplicationInfo appInfo = application.getPackageManager().getApplicationInfo(application.getPackageName(), PackageManager.GET_META_DATA);
            for (String key:appInfo.metaData.keySet()){
                if (key.startsWith("AppLike")){
                    String fullClass = LifeCycleConfig.getFullProxyClassName(appInfo.metaData.getString(key));
                    addAppLike(fullClass);
                }
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
    }

    private static IAppLike getClassForName(String className){
        IAppLike appLike = null;
        try {
            Object obj = Class.forName(className).newInstance();
            if (obj instanceof IAppLike) {
                appLike = (IAppLike) obj;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return appLike;
    }

    private static void scanClassFile(Application application) {
        try {
            scanClassFromAndroidManifest(application);
            Set<String> set = new HashSet<>();
            if (appLikeMap != null){
                set.addAll(appLikeMap);
            }
            if (!set.isEmpty()) {
                for (String className : set) {
                    IAppLike appLike = getClassForName(className);
                    if (appLike != null){
                        APP_LIKE_LIST.add(appLike);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 优先级比较器，优先级大的排在前面
     */
    static class AppLikeComparator implements Comparator<IAppLike> {

        @Override
        public int compare(IAppLike o1, IAppLike o2) {
            int p1 = o1.getPriority();
            int p2 = o2.getPriority();
            return p2 - p1;
        }
    }
}
